from django.conf import settings
from django import http
from django.utils.translation import check_for_language
from _translation import set_language_into_url

def set_language(request):
    next = (request.REQUEST.get('next')
        or request.META.get('HTTP_REFERER')
        or '/')
    lang_code = request.REQUEST.get('language')
    if lang_code:
        next = set_language_into_url(next, lang_code, 1)
    response = http.HttpResponseRedirect(next)
    if lang_code and check_for_language(lang_code):
        if hasattr(request, 'session') and request.method == 'POST':
            request.session['django_language'] = lang_code
        else:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
    return response
